#include "log.h"
#include <errno.h>
#include <stdarg.h>
#include <fcntl.h>

int Log::writeLog ( char * prompt, char * format, ... )
{
	va_list args ;
	char printBuffer[logBufferSZ] ;
	int saveErrNo ;
	struct tm *pTime ;
	time_t currentTime ;
	int fdLog = 0 ;

	saveErrNo = errno ;

	va_start ( args, format ) ;
	
	time ( &currentTime ) ;
	pTime = localtime ( &currentTime ) ;
	sprintf ( printBuffer, "(%02d,%02d) %02d:%02d:%02d - %s", pTime->tm_mon+1, 
			  pTime->tm_mday, pTime->tm_hour, pTime->tm_min, 
			  pTime->tm_sec, prompt 
			) ;
	vsprintf ( printBuffer+strlen(printBuffer), format, args ) ;
	
	va_end ( args ) ;

	fdLog = open ( logFile.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0664 ) ;
	if ( fdLog <= 0 )
		{
			printf ("Error to Open/Create file: %s\n", logFile.c_str() ) ;
			errno = saveErrNo ;
			return -1 ;
		}

	write (fdLog, printBuffer, strlen ( printBuffer ) ) ;
	close ( fdLog ) ;
	errno = saveErrNo ;

	return 0 ;
}
